using IGeekFan.AspNetCore.Knife4jUI;
using Microsoft.EntityFrameworkCore;
using NLog.Web;
using S.O.Interstructrue;
using S.O.Interstructrue.Base;
using S.O.Api.Read;
using System.Reflection;
using Yitter.IdGenerator;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(p =>
{
    var path = Path.Combine(AppContext.BaseDirectory, "S.O.Api.Read.xml");
    p.IncludeXmlComments(path,true);
});
// 数据库配置
builder.Services.AddDbContext<RBACDbContext>(x =>
{
    x.UseMySql(builder.Configuration.GetConnectionString("MySQL"), new MySqlServerVersion("5.7"));
});
// 中介者模式
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
// 自动映射
builder.Services.AddAutoMapper(typeof(RBACAutoMapper));
// 日志
builder.Host.UseNLog();
// 雪花ID
YitIdHelper.SetIdGenerator(new IdGeneratorOptions());
// 仓储
builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));


var app = builder.Build();

// 初始化数据库和种子数据
using (var scope = app.Services.CreateScope())
{
    var context = scope.ServiceProvider.GetRequiredService<RBACDbContext>();
    try
    {
        // 确保数据库已创建
        context.Database.EnsureCreated();
        
        // 初始化医疗测试数据
        S.O.Api.Read.DataSeed.MedicalDataSeed.SeedMedicalData(context);
    }
    catch (Exception ex)
    {
        var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
        logger.LogError(ex, "初始化数据库数据时发生错误");
    }
}

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    //app.UseSwaggerUI();
    app.UseKnife4UI();
}
// 跨域
app.UseCors(x => x.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());
app.UseAuthorization();

app.MapControllers();

app.Run();
